import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface User {
  id: number
  username: string
  name: string
  roles: string[]
  isAdmin?: boolean
  hasSetRoles?: boolean
  createdAt?: string
  updatedAt?: string
}

export interface UserState {
  user: User | null
  token: string | null
  currentRole: string | null
  isLoggedIn: boolean
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const currentRole = ref<string | null>(null)

  // 计算属性
  const isLoggedIn = computed(() => !!user.value && !!token.value)
  const hasRole = computed(() => (role: string) => {
    return user.value?.roles.includes(role) || false
  })

  // 操作
  const setUser = (userData: User) => {
    user.value = userData
  }

  const setToken = (tokenValue: string) => {
    token.value = tokenValue
  }

  const setCurrentRole = (role: string) => {
    if (user.value?.roles.includes(role)) {
      currentRole.value = role
    }
  }

  const login = (userData: User, tokenValue: string) => {
    setUser(userData)
    setToken(tokenValue)
  }

  const logout = () => {
    user.value = null
    token.value = null
    currentRole.value = null
  }

  const clearRole = () => {
    currentRole.value = null
  }

  return {
    // 状态
    user,
    token,
    currentRole,
    // 计算属性
    isLoggedIn,
    hasRole,
    // 操作
    setUser,
    setToken,
    setCurrentRole,
    login,
    logout,
    clearRole
  }
}, {
  persist: {
    key: 'rental-user',
    storage: localStorage,
    pick: ['user', 'token', 'currentRole']
  }
})
